<template>
  <div class='container'>
    <el-card shadow="hover">
      <el-container>
        <el-header
          class="tryTyping-titile"
          height="30px"
        >
          {{ $route.query.id ? '试题修改': '试题录入'}}
          <hr>
        </el-header>
        <!-- 页面表单 -->
        <el-main
          class="tryTyping-mainBox"
        >
        <el-form
          ref="form"
          :model="formData"
          :rules="rules"
        >

          <el-form-item
          label="学科:"
          prop="subjectID"
          >
          <el-select
              v-if="$route.query.id"
              clearable
              @change="subjectChange"
              v-model="formData.subjectID"
            >
              <el-option
              :label="formData.subjectName"
              :value="formData.subjectID"></el-option>
            </el-select>
            <el-select
              v-else
              clearable
              @change="subjectChange"
              v-model="formData.subjectID"
              placeholder="请选择学科">
              <el-option
              v-for="(item, index) in subjectList"
              :key="index"
              :label="item.subjectName"
              :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
          prop="catalogID"
          label="目录:">
          <el-select
            v-if="$route.query.id"
            @change="catalogutChange"
            v-model="formData.catalogID"
          >
          <el-option
            :label="formData.directoryName"
            :value="formData.catalogID">
            </el-option>
          </el-select>
            <el-select
              v-else
              @change="catalogutChange"
              v-model="formData.catalogID"
              placeholder="请选择目录">
              <el-option
              v-for="item in catalogutList"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id">
              </el-option>
            </el-select>

          </el-form-item>

          <el-form-item
          prop="enterpriseID"
          label="企业:">
            <el-select v-model="formData.enterpriseID" placeholder="请选择企业">
              <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.company"
              :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            prop="province"
            label="城市:">
            <el-select
              @change="getProvince"
              v-model="formData.province" placeholder="请选择城市">
              <el-option
                v-for="(item, index) in citys"
                :key="index"
                :label="item"
                :value="item"
                ></el-option>
            </el-select>

            <el-select v-model="formData.city" placeholder="请选择地区">
              <el-option
              v-for="(item, index) in provinces"
              :key="index"
              :label="item"
              :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
          prop="direction"
          label="方向:">
            <el-select v-model="formData.direction" placeholder="请选择兴趣方向">
              <el-option
              v-for="(item, index) in direction"
              :key="index"
              :label="item"
              :value="item"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="题型:"
            prop="questionType"
          >
              <el-radio-group
                v-model="formData.questionType"
                @change="radioChange"
              >
              <el-radio
                v-for="(item, index) in questionType"
                :key="index"
                :label="item.value"
                >{{ item.label }}</el-radio>
              </el-radio-group>
          </el-form-item>

          <el-form-item
            label="难度:"
            prop="difficulty"
          >
              <el-radio-group
              @change="difficultyChange"
              v-model="formData.difficulty"
              >
              <el-radio
              v-for="(item, index) in difficulty"
                :key="index"
                :label="item.value"
                >{{ item.label }}</el-radio>
              </el-radio-group>
          </el-form-item>

          <!-- 题干 富文本 -->
          <el-form-item
            label="题干:"
            prop="question"
          >
          <el-row>
            <div>
              <quill-editor
              v-model="formData.question"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @change="onEditorChange($event)">
            </quill-editor>
            </div>
          </el-row>
          </el-form-item>

            <!-- 选项  单选 -->
          <el-form-item
            v-show="formData.questionType === '1'"
            label="选项:"
            prop="options"
          >
          <el-row></el-row>

            <el-row
              v-show="formData.questionType === '1'"
              v-for="(item, index) in oneCheckRadio"
              :key="index"
              type="flex"
              align="middle"
              class="options-item"
            >
            <el-col :span="1">
              </el-col>
              <el-col :span="1">
                <el-radio
                  @change="optionsChange"
                  v-model="code"
                  :label="item.code">{{ item.code }}:</el-radio>
              </el-col>
              <el-col :span="6">
                <el-input
                  :disabled="isActive"
                  v-model="item.title"
                  @focus="oneChekFoucs"
                  class="options-firltInput"
                  placeholder="请输入内容"></el-input>
              </el-col>

              <el-col :span="8">
                <el-upload
                  class="options-upload"
                  action="#"
                  :http-request="hanldeUpload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  list-type="picture-card"
                  :limit:="1"
                  >
                  <img
                    :src="item.img"
                    class="avatar">
                  <i class="el-icon-plus">上传图片</i>
                </el-upload>
              </el-col>
            </el-row>

            <!-- 新增选项  -->
            <el-row
              type="flex"
            >
            <el-col :span="12" :offset="1">
            <el-button
                :disabled="formData.questionType == 1 ? true : false"
                @click="addChekOptions"
              type="danger">+增加选项与答案</el-button>

            </el-col>
            </el-row>
            <el-dialog
              title="提示"
              :visible="dialogVisible"
              width="30%"
              >
              <el-input v-model="addChekOptionsIpt"></el-input>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onAddoptionsCheck">确 定</el-button>
              </span>
            </el-dialog>
          </el-form-item>

          <!--  选项 多选 -->
          <el-form-item
            v-show="formData.questionType === '2'"
            label="选项:"
            prop="options"
          >
          <el-row></el-row>

            <el-row
              v-show="formData.questionType === '2'"
              v-for="(item, index) in checkRadio"
              :key="index"
              type="flex"
              align="middle"
              class="options-item"
            >
            <el-col :span="1">
              </el-col>
              <el-col :span="1">
                <el-checkbox-group
                v-model="codeList">
                  <el-checkbox :label="item.code">{{ item.code }}:</el-checkbox>
                </el-checkbox-group>
              </el-col>
              <el-col :span="6">
                <el-input
                  v-model="item.title"
                  class="options-firltInput"
                  placeholder="请输入内容"></el-input>
              </el-col>

                <el-col :span="8"
                >
                <el-upload
                  class="options-upload"
                  action="#"
                  :http-request="hanldeUpload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  list-type="picture-card"
                  :limit:="1"
                  >
                  <img
                    :src="item.img"
                    class="avatar">
                  <i class="el-icon-plus"
                    @click="codeListChange(item)"
                  >上传图片</i>
                </el-upload>
              </el-col>
            </el-row>

            <!-- 新增选项  -->
            <el-row
              type="flex"
            >
            <el-col :span="12" :offset="1">
            <el-button
                :disabled="formData.questionType == 1 ? true : false"
                @click="addChekOptions"
              type="danger">+增加选项与答案</el-button>

            </el-col>
            </el-row>
            <el-dialog
              title="提示"
              :visible="dialogVisible"
              width="30%"
              >
              <el-input v-model="addChekOptionsIpt"></el-input>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onAddoptionsCheck">确 定</el-button>
              </span>
            </el-dialog>
          </el-form-item>

            <!-- 解析视频 -->
            <el-form-item label="解析视频:">
              <el-input class="options-video-input" v-model="formData.videoURL"></el-input>
            </el-form-item>

            <!-- 答案解析 -->
            <el-form-item
              prop="answer"
              label="答案解析:">
              <quill-editor
                v-model="formData.answer"
                ref="answerParseQuillEditor"
                :options="parseeditorOption"
                @change="onParseEditorChange($event)">
              </quill-editor>
            </el-form-item>

            <!-- 题目备注 -->
            <el-form-item label="题目备注:">
              <el-input
              autosize
              type="textarea"
              class="options-video-input"
              v-model="formData.remarks"></el-input>
            </el-form-item>

            <!-- 试题标签 -->
            <el-form-item
              prop="tags"
              label="试题标签:"
            >
            <el-select
              v-if="$route.query.id"
              multiple
              v-model="detailTags"
              placeholder="请选择试题标签">
              <el-option
              v-for="(item, index) in formData.tags"
              :key="index"
              :label="item"
              :value="item"
              >
              </el-option >
            </el-select>

            <el-select
              v-else
              v-model="formData.tags"
              multiple
              placeholder="请选择试题标签">
              <el-option
              v-for="(item, index) in testQusetions"
              :key="index"
              :label="item.catalog"
              :value="item.number"
              >
              </el-option >
            </el-select>
            </el-form-item>
          <el-form-item>
            <el-button
              v-if="$route.query.id"
              @click="eiditQuestion"
            type="danger">修改</el-button>
            <el-button
              v-else
              type="primary"
              @click="addQusetions"
            >提交</el-button>
          </el-form-item>
        </el-form>
        </el-main>
      </el-container>
    </el-card>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
import { quiltEditor, answerPaeseEditor } from '@/quil.config.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { list } from '@/api/hmmm/subjects.js'
import { list as catalogutList } from '@/api/hmmm/directorys.js'
import { list as companyList } from '@/api/hmmm/companys.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// 基础 题库添加
import { list as questions, add, detail, update } from '@/api/hmmm/questions.js'
const cos = new COS({
  SecretId: 'AKIDkJcePu85pJWR5SZx4uTlmVy93g38xVno',
  SecretKey: 'lGUS9akdGchV2IGxNWP1LOAftqWv3uUm'
})
export default {
  name: 'tryTyping',
  data () {
    return {
      // 城市
      citys: [],
      // 城市下属区域
      provinces: '',

      // 表单
      formData: {
        subjectID: null,
        catalogID: '',
        // 企业id
        enterpriseID: '',
        city: '',
        province: '',
        // 方向
        direction: '',
        // 题型选项
        questionType: '1',
        difficulty: '1',
        // 题干
        question: '',
        options: [
          {
            code: '',
            title: '',
            img: '',
            isRight: true
          }
        ],
        videoURL: '',
        // 题目备注
        remarks: '',
        tags: '',
        // 答题解析
        answer: ''
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择科目', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择兴趣方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择一项', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请选择输入', trigger: 'bulr' }
        ],
        options: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'bulr' }
        ],
        tags: [
          { required: true, message: '请选择试题标签', trigger: 'change' }
        ]
      },
      editorOption: quiltEditor,
      parseeditorOption: answerPaeseEditor,
      // 获取学科列表
      subjectList: [],
      subjects: {
        page: 1,
        pagesize: 100,
        subjectName: ''
      },
      // 目录列表
      catalogutList: [],
      // 企业列表
      companyList: [],
      // 方向
      direction,
      questionType,
      difficulty,
      // // img
      // imgUrl: '',
      // // 多选
      // imgList: [],
      // 试题 列表
      testQusetions: [],
      // 选项 按钮
      checkRadio: [
        { code: 'A', title: '', img: '', isRight: true },
        { code: 'B', title: '', img: '', isRight: true },
        { code: 'C', title: '', img: '', isRight: true },
        { code: 'D', title: '', img: '', isRight: true }
      ],
      // 选项单选
      oneCheckRadio: [
        { code: 'A', title: '', img: '', isRight: true },
        { code: 'B', title: '', img: '', isRight: true },
        { code: 'C', title: '', img: '', isRight: true },
        { code: 'D', title: '', img: '', isRight: true }
      ],
      detailTags: [],
      // 复选框
      checkRadios: [],
      // 单选项框值
      checkRadioVal: '',
      // 选项 单选radio
      code: '',
      // 新增 选项按钮
      dialogVisible: false,
      // 多选框选中列表;
      codeList: [],
      // 当前复选框选中 item
      currentItem: {},
      // 新增 dialog
      addChekOptionsIpt: '',
      // 所有选项
      letter: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
        'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
        'W', 'X', 'Y', 'Z']
    }
  },
  async mounted () {
    // this.$route.query.id = 29
    this.citys = provinces()

    if (this.$route.query.id) {
      const { data } = await detail({ id: 29 })
      if (data.questionType === '1') {
        this.code = data.options[0].code
        this.oneCheckRadio.map(item => {
          if (item.code === this.code) {
            item.title = data.options[0].title
          }
          return item
        })
      } else if (data.questionType === '2') {
        this.codeList = data.options.map(item => {
          return item.code
        })
        this.checkRadio = data.options
      }
      data.tags = data.tags.split(',')
      this.formData = data
      console.log(data)
    } else {
      // 基础学科列表
      const { data: { items } } = await list(this.subjects)
      this.subjectList = items
    }

    // 获取企业列表
    const { data: { items: companys } } = await companyList({ page: 1, pagesize: 10 })
    this.companyList = companys
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res, file)
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    // 题干富文本
    onEditorChange(val) {
    },
    // 答题解析富文本
    onParseEditorChange(val) {

    },
    // 获得 城市 下属地区
    getProvince(val) {
      this.formData.city = ''
      this.provinces = citys(val)
    },
    async subjectChange(val) {
      const { data: { items } } = await catalogutList({ page: 1, paggesize: 10, subjectID: val })
      this.catalogutList = items
    },
    // 目录change
    async catalogutChange(val) {
      const { data: { items } } = await questions({ page: 1, pagesize: 10, subjectID: this.formData.subject })
      this.testQusetions = items
    },
    // 题型 change
    radioChange(val) {
      this.formData.questionType = val
      console.log(val)
    },
    // 难度change
    async difficultyChange(val) {
    },
    // 单选 改变
    optionsChange(val) {
      // this.formData.options[0].code = this.formData.options[0].code.toString()
      this.formData.options = this.oneCheckRadio.filter(item => {
        return item.code === val
      })
    },
    // 单选 input foucs
    oneChekFoucs() {
      this.oneCheckRadio.forEach(item => {
        item.title = ''
      })
    },
    // 新增 选项 弹出dialog
    addChekOptions() {
      this.dialogVisible = true
    },
    // 新增 选项
    onAddoptionsCheck() {
      if (this.letter.includes(this.addChekOptionsIpt)) {
        const item = { code: this.addChekOptionsIpt, title: '', img: '', isRight: true }
        const a = this.checkRadio.some(t => {
          return t.code === item.code
        })
        if (!a) {
          this.checkRadio.push(item)
        } else {
          this.$message.error('已经有这个选项啦~~~')
          this.addChekOptionsIpt = ''
        }
      }

      this.dialogVisible = false
    },
    // 多选 change
    codeListChange(val) {
      console.log(val)
      this.currentItem = val
    },
    // 表单提交
    addQusetions() {
      this.formData.questionType = this.formData.questionType.toString()
      this.formData.difficulty = this.formData.difficulty.toString()
      this.formData.tags = this.formData.tags.toString()
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          await add(this.formData).then(res => {
            this.$message.success('录入成功~~~~')
            this.$refs.form.resetFields()
          })
        } else {
          return this.$message.error('请检查必填项~~~~')
        }
      })
    },
    // 表单修改
    async eiditQuestion() {
      console.log(this.formData)
      this.formData.tags = this.detailTags.toString()
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          await update(this.formData).then(res => {
            this.$refs.form.resetFields()
            this.$message.success('修改成功~~')
          })
        } else {
          const { data } = await detail({ id: 29 })
          data.tags = data.tags.split(',')
          this.formData = data
          this.$message.error('请检查必填项~~~')
        }
      })
    },
    hanldeUpload(params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'employees-1308067124', /* 必须 */
          Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */
          Key: params.file.name, /* 必须 */
          Body: params.file,
          StorageClass: 'STANDARD'
        }, (err, data) => {
          // 单选 图片
          if (!err && data.statusCode === 200 && this.formData.questionType === '1') {
            if (this.formData.questionType === '1' && this.code) {
              this.oneCheckRadio.find(item => {
                item.img = ''
                if (item.code === this.code) {
                  item.img = 'https://' + data.Location
                }
              })
            }
          }
          // 多选图片
          if (!err && data.statusCode === 200 && this.formData.questionType === '2') {
            this.checkRadio.forEach((item, index) => {
              if (item.code === this.currentItem.code) {
                this.checkRadio[index].img = 'https://' + data.Location
              }
            })
            this.formData.options = this.checkRadio.filter(t => {
              return t && this.codeList.includes(t.code)
            })
          }
        })
      }
    }
  },
  computed: {
    isActive: function() {
      return this.checkRadio.includes({ code: this.code })
    }
  }
}
</script>

<style scoped lang='less'>
.container{
  padding: 10px;
  .tryTyping-titile{
    padding-left: 0px;
    padding-right: 0px;
  }

  /deep/ .tryTyping-mainBox{
    padding-left: 50px;
    .options-item:nth-child(n){
      margin-left: -5px;
    }
    .options-item{
      margin: 10px;
      .el-upload.el-upload--picture-card{
      display: grid;
      width: 100px;
      height: 50px;
      place-items: center;
        i{
          font-size: 14px;
        }
      }

    }
  }
  /deep/ .options-video-input{
        width: 20%;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 30px;
    height: 30px;
    display: block;
  }
  /deep/ .el-upload.el-upload--picture-card{
    overflow: hidden;
  }
}
</style>
